package com.wtwd.campus.vcom.utils;

import com.alibaba.fastjson.JSONObject;
import com.wtwd.campus.utils.DateUtils;
import com.wtwd.campus.utils.GPSUtils;
import com.wtwd.campus.utils.HttpclientUtil;
import com.wtwd.campus.vcom.dao.RequestRecordMapper;
import com.wtwd.campus.vcom.entity.VcomRequestRecord;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 * @Author: ldaoliang
 * @DateTime: 2022/1/7 15:12
 * @Description:
 */
@Service
public class VcomPushUtils {

    private final static Logger logger = LoggerFactory.getLogger(VcomPushUtils.class);

    @Autowired
    RequestRecordMapper requestRecordMapper;

    /**
     * 完成命令（修改状态及推送）
     *
     * @param imei
     * @param commandNumber
     * @param type
     * @param status
     */
    public void commandComplete(String imei, String commandNumber, int type, int status) {
        // 1、修改对应requestRecord的状态（先改为status和推送完成，如果推送失败则该状态为失败）
        VcomRequestRecord requestRecord = requestRecordMapper.getRequestRecordByDescOne(imei, commandNumber, type);
        if (requestRecord != null) {
            boolean pushResult = pushMessageResult(requestRecord.getRequestId(), status, imei);
            requestRecordMapper.updatePushStatus(requestRecord.getId(), pushResult ? 1 : 2, System.currentTimeMillis());
        }
    }

    public boolean pushMessageResult(String requestId, int status, String imei) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("imei", imei);
        jsonObject.put("requestId", requestId);
        jsonObject.put("result", status);
        try {
            String s = HttpclientUtil.httpPost("https://ncp.czbanbantong.com/gw/iotapi/iot/message/received", jsonObject);
            logger.info("/威科姆推送消息返回结果：result = {}", s);
            JSONObject json = JSONObject.parseObject(s);
            logger.info("威科姆推送消息地址={}", "https://ncp.czbanbantong.com/gw/iotapi/iot/message/received");
            logger.info("威科姆推送返回值={}", s);
            if (String.valueOf(json.get("code")).equals("0")) {
                logger.info("/威科姆推送消息处理结果成功，requestId = {},imei= {},status={}", requestId, imei, status);
                return true;
            }
        } catch (Exception e) {
            System.out.println("推送失败");
            logger.info("/威科姆推送消息处理结果失败： requestId = {},imei= {},status={}", requestId, imei, status);
        }
        return false;
    }


    /**
     * @param latitude
     * @param longitude
     * @param address
     * @param type      1：sos告警   2：低电量告警  3：进入围栏告警  4： 离开围栏告警
     * @param info
     * @param warnTime
     * @param imei
     * @return
     */
    public boolean pushWarning(double latitude, double longitude, String address, int type, String info, long warnTime, String imei, String fenceName, String fenceId) {
        Map<String, String> map = new HashMap<>();
        map.put("alarmType", String.valueOf(type));
        map.put("imei", imei);
        map.put("dataTime", DateUtils.format(new Date(warnTime), DateUtils.dateFormat4));
        JSONObject data = new JSONObject();
        data.put("originalLongitude", String.valueOf(longitude));
        data.put("originalLatitude", String.valueOf(latitude));
        //以下转化为高德经纬度坐标
        if (latitude != 0 && longitude != 0) {
            double[] gdLocations = GPSUtils.gps84_To_Gcj02(latitude, longitude);
            data.put("gaodeLongitude", gdLocations[0]);
            data.put("gaodeLatitude", gdLocations[1]);
            double[] baiduLocations = GPSUtils.gps84_To_bd09(latitude, longitude);
            data.put("baiduLongitude", baiduLocations[0]);
            data.put("baiduLatitude", baiduLocations[1]);
        }
        data.put("fenceName", fenceName);
        data.put("fenceId", fenceId);
        data.put("address", address);
        data.put("info", info);
        map.put("data", data.toJSONString());
        String s = null;
        try {
            s = doPostJson("https://ncp.czbanbantong.com/gw/iotapi/iot/alarm", map);
        } catch (Exception e) {
            logger.info("推送异常");
            e.printStackTrace();
        }
        logger.info("威科姆推送告警地址={}", "https://ncp.czbanbantong.com/gw/iotapi/iot/alarm");
        logger.info("威科姆推送返回值={}", s);
        if (StringUtils.isBlank(s)) {
            logger.info("/威科姆告警信息推送失败，类型={},imei={}", type, imei);
            return false;
        }
        JSONObject json = JSONObject.parseObject(s);
        if (String.valueOf(json.get("code")).equals("0")) {
            logger.info("/威科姆告警信息推送成功，类型={},imei={}", type, imei);
            return true;
        }
        logger.info("/威科姆告警信息推送失败，类型={},imei={}", type, imei);
        return false;
    }

    /*  public static void main(String[] args) {
          pushWarning(34.82511484613315,113.5571253051376,"河南省郑州市中原区枫杨街道郑州威科姆科技股份有限公司(莲花街)威科姆大厦",3,"进入电子围栏:cs",1658297752958L,"866248053262737","cs","cs");
      }
  */
    public void pushAndUpdateRequestStatus(int id, String requestId, int status, int type, String imei) {
        boolean pushResult = pushMessageResult(requestId, status, imei);
        requestRecordMapper.updatePushStatus(id, pushResult ? 1 : 2, System.currentTimeMillis());
    }


    public String doPostJson(String url, Map<String, String> map) throws Exception {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
            try {
                if (map.size() != 0) {
                    List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : map.keySet()) {
                        paramList.add(new BasicNameValuePair(key, map.get(key)));
                    }
                    // 模拟表单
                    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "utf-8");
                    httpPost.setEntity(entity);
                }
                response = httpClient.execute(httpPost);
                resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }


}
